package com.ms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.mapper.UserManageMapper;
import com.ms.pojo.Employee;
import com.ms.service.UserManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserManageServiceImpl implements UserManageService {
    @Autowired
    private UserManageMapper userManageMapper;

    /**
     * 获取所有员工
     */
    @Override
    public IPage<Employee> getAllEmployees(int page, int size) {
        Page<Employee> employeePage = new Page<>(page, size);

        // 使用自定义的分页查询方法
        List<Employee> employees = userManageMapper.selectAllWithPagination(
                (int) ((employeePage.getCurrent() - 1) * employeePage.getSize()),
                (int) employeePage.getSize()
        );

        // 设置总记录数（需要额外查询总数）
        long total = userManageMapper.countAll();

        employeePage.setRecords(employees);
        employeePage.setTotal(total);

        return employeePage;
    }
    /**
     * 根据ID获取员工
     */
    @Override
    public Employee getEmployeeById(Integer empId) {
        if (empId == null){
            return null;
        }
        return userManageMapper.selectById(empId);
    }

    /**
     * 添加员工
     */
    @Override
    public boolean addEmployee(Employee employee) {
        try {
            //设置默认更新时间
            employee.setUpdateTime(new Date());
            return userManageMapper.insert(employee) > 0;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新员工信息
     */
    @Override
    public boolean updateEmployee(Employee employee) {
        if (employee.getEmpId() == null){
            return false;
        }
        try {
            //更新时刷新更新时间
            employee.setUpdateTime(new Date());
            return userManageMapper.update(employee) > 0;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除员工
     */
    @Override
    public boolean deleteEmployee(Integer empId) {
        if (empId == null){
            return false;
        }
        try {
            return userManageMapper.deleteById(empId) > 0;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
